﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FlashPay.Service.Impl
{
    using FlashPay.DAO.Bank;
    using FlashPay.DAO.Interface;
    using FlashPay.DAO.Sys;
    using FlashPay.EF;
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request.Payment;
    using FlashPay.Entity.Response.Bank;
    using FlashPay.Entity.Response.Company;
    using FlashPay.Entity.Response.Payment;
    using FlashPay.Entity.Response.Sys;
    using FlashPay.Service.Interface;
    using FlashPay.Util;
    using Microsoft.AspNetCore.Http;
    using Newtonsoft.Json;
    using System.Linq;
    using System.Text.RegularExpressions;

    public class PaymentRecordServiceImpl : PaymentRecordService
    {
        /// <summary>
        /// 功能权限数据接口
        /// </summary>
        private readonly PaymentRecordDao _paymentRecordDao;

        /// <summary>
        /// 功能权限数据接口
        /// </summary>
        private readonly PaymentInterfaceDao _paymentInterfaceDao;
        
        /// <summary>
        ///  银行类型数据接口
        /// </summary>
        private readonly BankInfoDAO _bankInfoDao;

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 菜单数据接口
        /// </summary>
        private readonly MenuDao _menuDao;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// 银行数据接口
        /// </summary>
        private readonly BankDao _bankDao;

        /// <summary>
        /// 配置
        /// </summary>
        private readonly SysConfigDao _sysConfigDao;

        /// <summary>
        /// 实体付款记录
        /// </summary>
        private readonly RecordRealDao _recordRealDao;

        /// <summary>
        /// 余额变化表
        /// </summary>
        private readonly AdjustBalanceDao _adjustBalanceDao;

        /// <summary>
        /// 
        /// </summary>
        public readonly IHttpContextAccessor _accessor;

        /// <summary>
        /// 上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 功能权限数据接口
        /// </summary>
        /// <param name="permission"></param>
        public PaymentRecordServiceImpl(PaymentRecordDao paymentRecordDao, PaymentInterfaceDao paymentInterfaceDao, BankInfoDAO bankInfoDao, CompanyDao companyDao, MenuDao menuDao, 
            LogRecord logRecord, LogDao logDao, BankDao bankDao, SysConfigDao sysConfigDao, RecordRealDao recordRealDao, AdjustBalanceDao adjustBalanceDao, IHttpContextAccessor accessor, FlashPayContext context)
        {
            _paymentRecordDao = paymentRecordDao;
            _paymentInterfaceDao = paymentInterfaceDao;
            _bankInfoDao = bankInfoDao;
            _companyDao = companyDao;
            _menuDao = menuDao;
            _logRecord = logRecord;
            _logDao = logDao;
            _bankDao = bankDao;
            _sysConfigDao = sysConfigDao;
            _recordRealDao = recordRealDao;
            _adjustBalanceDao = adjustBalanceDao;
            _accessor = accessor;
            _context = context;
        }

        /// <summary>
        /// 根据编号获取余额变化记录
        /// </summary>
        /// <param name="orderNo">编号</param>
        /// <returns>Company</returns>
        public RecordRealResponse Get(long orderNo)
        {
            var recordRealResponse = new RecordRealResponse();

            var paymentRecord = _paymentRecordDao.Get(orderNo);
            if (paymentRecord != null)
            {
                recordRealResponse.OrderNo = paymentRecord.OrderNo.ToString();
                var company = _companyDao.GetById(paymentRecord.CompanyId);
                if (company != null)
                {
                    recordRealResponse.CompanyName = company.CompanyName;
                }
                recordRealResponse.ClientAccountName = paymentRecord.WithdrawalAccountName;
                recordRealResponse.Amount = paymentRecord.WithdrawalAmount.ToString("#0.00");
                return recordRealResponse;
            }
            else {
                return null;
            }
            
        }

                /// <summary>
        /// 获取第三方支付类型
        /// </summary>
        /// <returns></returns>
        public JResult<List<SysConfigResponse>> GetSysConfigList()
        {
            var result = new JResult<List<SysConfigResponse>>()
            {
                Success = false
            };

            var sysConfigList = _sysConfigDao.GetList(new SysConfigQuery() { ConfigCode = "PaymentInterface" });
            if (sysConfigList != null && sysConfigList.Any())
            {
                var sysConfigResponse = new List<SysConfigResponse>();
                sysConfigList.ForEach(item => {
                    sysConfigResponse.Add(new SysConfigResponse()
                    {
                        ConfigValue = item.ConfigValue,
                        ConfigContent = item.ConfigContent
                    });
                });
                result.Success = true;
                result.Data = sysConfigResponse;
            }

            return result;
        }

        /// <summary>
        /// 订单验证
        /// </summary>
        /// <param name="orderNo">付款卡订单号</param>
        public JResult VerificationOrder(int companyId, long orderNo)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var paymentRecords = _paymentRecordDao.GetList(new PaymentRecordQuery() { CompanyId = companyId });
                if (paymentRecords != null && paymentRecords.Any())
                {
                    var paymentRecord = paymentRecords.FirstOrDefault(p => p.OrderNo == orderNo);
                    if (paymentRecord == null)
                    {
                        throw new Exception("你没有操作当前付款订单的权限！");
                    }

                    result.Success = true;
                }
                else
                {
                    throw new Exception("你没有操作当前付款订单的权限！");
                }
            }
            catch (Exception ex) {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 付款记录取消
        /// </summary>
        /// <param name="orderNo">编号</param>
        /// <returns>JResult</returns>
        public JResult PaymentRecordCancel(long orderNo,string userName)
        {
            var result = new JResult() {
                Success = false
            };

            try
            {
                var paymentRecord = _paymentRecordDao.Get(orderNo);
                if (paymentRecord == null)
                {
                    throw new Exception("付款订单不存在");
                }

                if (paymentRecord.PaymentStatus != PaymentRecordPaymentStatus.未付款.GetHashCode()) {
                    throw new Exception("付款订单状态已发生变化，无法取消");
                }

                //取消订单的部分，能不能新增一个判断，就是如果已经配到付款卡了，就不允许取消
                if (paymentRecord.ReadDate !=null) {
                    throw new Exception("操作失败，该订单已付款中");
                }


                var status = _paymentRecordDao.UpdatePaymentStatus(paymentRecord.OrderNo, (sbyte)PaymentRecordPaymentStatus.取消付款.GetHashCode());
                if (status)
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.PaymentRecord_Reject_Cancel.GetHashCode();
                    _logRecord.CreateName = userName;
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"付款记录取消成功,订单号：{orderNo}";
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "取消付款订单成功！";
                }
                else {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.PaymentRecord_Reject_Cancel.GetHashCode();
                    _logRecord.CreateName = userName;
                    _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"付款记录取消失败,订单号：{orderNo}";
                    _logDao.Insert(_logRecord);

                    result.SuccessMessage = "取消付款订单失败！";
                }
            }
            catch (Exception ex) {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 付款记录重置
        /// </summary>
        /// <param name="orderNo">编号</param>
        /// <returns>JResult</returns>
        public JResult PaymentRecordReset(long orderNo, string userName)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {

                var paymentRecord = _paymentRecordDao.Get(orderNo);
                if (paymentRecord == null)
                {
                    throw new Exception("付款订单不存在");
                }
                if (paymentRecord.NoticeStatus != PaymentRecordNoticeStatus.通知失败.GetHashCode() || paymentRecord.NoticeTimes != 5)
                {
                    throw new Exception("付款订单通知状态已发生变化或通知次数等于5");
                }

                //通知次数
                var status = _paymentRecordDao.UpdateNoticeStatus(paymentRecord.OrderNo, (sbyte)PaymentRecordNoticeStatus.通知失败.GetHashCode(), 1);
                if (status)
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.PaymentRecord_ResetNotice.GetHashCode();
                    _logRecord.CreateName = userName;
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"付款记录重置成功,订单号：{orderNo}";
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "重置付款订单成功！";
                }
                else
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.PaymentRecord_ResetNotice.GetHashCode();
                    _logRecord.CreateName = userName;
                    _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"付款记录重置失败,订单号：{orderNo}";
                    _logDao.Insert(_logRecord);

                    result.SuccessMessage = "重置付款订单失败！";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 付款确认
        /// </summary>
        /// <param name="request">参数</param>
        public JResult PaymentConfirm(PaymentConfirmRequest request)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {

                var paymentRecord = _paymentRecordDao.Get(request.OrderNo);
                if (paymentRecord == null)
                {
                    throw new Exception("付款订单不存在");
                }

                if (paymentRecord.NoticeStatus != (sbyte)PaymentRecordConfirmStatus.未处理.GetHashCode())
                {
                    throw new Exception("付款订单通知状态已发生变化，无法确认");
                }

                var status = _paymentRecordDao.PaymentConfirm(new PaymentConfirmRequest() {
                    OrderNo = request.OrderNo,
                    ConfirmUID = request.ConfirmUID,
                    ConfirmName = request.ConfirmName,
                    ConfirmStatus = (sbyte)PaymentRecordConfirmStatus.人工审核通过.GetHashCode(),
                    ConfirmDate = DateTime.Now
                });
                if (status)
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.PaymentRecord_Audit.GetHashCode();
                    _logRecord.CreateName = request.ConfirmName;
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"付款记录确认成功,订单号：{request.OrderNo}";
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "确认付款订单成功！";
                }
                else
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.PaymentRecord_Audit.GetHashCode();
                    _logRecord.CreateName = request.ConfirmName;
                    _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"付款记录确认失败,订单号：{request.OrderNo}";
                    _logDao.Insert(_logRecord);

                    result.SuccessMessage = "确认付款订单失败！";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 重新付款
        /// </summary>
        /// <param name="request"></param>
        public JResult RenewPayment(RenewPaymentRequest request)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var paymentRecord = _paymentRecordDao.Get(request.OrderNo);
                if (paymentRecord == null)
                {
                    throw new Exception("操作失败：付款订单不存在");
                }

                if(paymentRecord.PaymentType != (sbyte)PaymentRecordPaymentType.秒付宝支付)
                {
                    throw new Exception("操作失败：付款类型只能秒付宝支付");
                }

                if(paymentRecord.PaymentStatus != (sbyte)PaymentRecordPaymentStatus.付款中)
                {
                    throw new Exception("操作失败：只有付款状态为付款中才能重新付款");
                }

                var paymentRecordNoticeStatus = new List<sbyte>()
                {
                    (sbyte)PaymentRecordNoticeStatus.未通知.GetHashCode()
                };

                if (!paymentRecordNoticeStatus.Contains(paymentRecord.NoticeStatus))
                {
                    throw new Exception("操作失败：通知状态只能未通知");
                }

                if (paymentRecord.RecordRealOrderNo != null) {
                    throw new Exception("操作失败：匹配流水号不为空");
                }

                var status = _paymentRecordDao.RenewPayment(new RenewPaymentRequest()
                {
                    OrderNo = request.OrderNo
                });
                if (status)
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.PaymentRecord_Audit.GetHashCode();
                    _logRecord.CreateName = request.UserName;
                    _logRecord.CreateUid = request.UserId;
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.OrderNo = request.OrderNo;
                    _logRecord.LogRemark = $"手动重新付款成功,订单号：{request.OrderNo}";
                    _logRecord.CompanyId = request.CompanyId;
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "重新付款订单成功！";
                }
                else
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.PaymentRecord_Audit.GetHashCode();
                    _logRecord.CreateName = request.UserName;
                    _logRecord.CreateUid = request.UserId;
                    _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.OrderNo = request.OrderNo;
                    _logRecord.LogRemark = $"手动重新付款失败,订单号：{request.OrderNo}";
                    _logRecord.CompanyId = request.CompanyId;
                    _logDao.Insert(_logRecord);

                    result.SuccessMessage = "付款记录重新付款失败！";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 添加付款记录
        /// </summary>
        /// <param name="request">参数</param>
        /// <returns></returns>
        public JResult PaymentRecordAdd(PaymentRecordAddRequest request)
        {
            var result = new JResult() {
                Success = false
            };

            try {
                //公司验证
                var companys = this.GetCompany(request.CurrentCompanyId, 2);
                if (!companys.Any(p => p.CompanyID == request.CompanyId)) {
                    throw new Exception("公司名称不属于当前用户公司及子公司");
                }

                //获取公司
                var company = _menuDao.GetById(request.CompanyId);
                if (company == null) {
                    throw new Exception("选择公司不存在");
                }

                //客户订单号
                if (string.IsNullOrEmpty(request.WithdrawalOrderNo)) {
                    throw new Exception("客户单号必须介于 3 和 40 之间");
                }
                var withdrawalOrderNoReg = new Regex(@"^[A-Za-z0-9]+$");
                if (!withdrawalOrderNoReg.IsMatch(request.WithdrawalOrderNo))
                {
                    throw new Exception("客户单号由英文、数字组成");
                }
                if (request.WithdrawalOrderNo.Length < 3 || request.WithdrawalOrderNo.Length > 40) {
                    throw new Exception("客户单号必须介于 3 和 40 之间");
                }

                //付款金额必须大于0
                if (request.WithdrawalAmount <= 0) {
                    throw new Exception("付款金额必须大于零");
                }

                //银行名称
                var bankInfo = _bankInfoDao.GetByBankCode(request.WithdrawalCardBankFlag);
                if (bankInfo == null) {
                    throw new Exception("选择客户银行");
                }

                //客户姓名
                if (string.IsNullOrEmpty(request.WithdrawalAccountName)) {
                    throw new Exception("客户姓名必须介于 2 和 40 之间");
                }
                if (request.WithdrawalAccountName.Length < 2 || request.WithdrawalAccountName.Length > 40) {
                    throw new Exception("客户姓名必须介于 2 和 40 之间");
                }

                //客户卡号
                if (string.IsNullOrEmpty(request.WithdrawalCardNumber))
                {
                    throw new Exception("客户卡号必须介于 15 和 20 之间");
                }
                if (request.WithdrawalCardNumber.Length < 15 || request.WithdrawalCardNumber.Length > 20)
                {
                    throw new Exception("客户卡号必须介于 15 和 20 之间");
                }
                //单号统一验证
                var paymentRecords = _paymentRecordDao.CheckOrder(new PaymentRecordQuery() { CompanyId = request.CompanyId, WithdrawalOrderNo = "ts_" + request.WithdrawalOrderNo });
                if (paymentRecords != null && paymentRecords.Any())
                {
                    throw new Exception("单号重复");
                }

                //付款费率
                var feeRatio = (decimal)company.DepositRate;
                //付款费用
                var feeTotal = (decimal)company.DepositRate * request.WithdrawalAmount;

                var paymentRecord = new PaymentRecord() {
                    CompanyId = company.CompanyId,
                    PaymentRemark = request.PaymentRemark,
                    CreateDate = DateTime.Now,
                    ConfirmStatus = (sbyte)PaymentRecordConfirmStatus.未处理.GetHashCode(),
                    ConfirmDate = DateTime.Now,
                    PaymentType = _paymentInterfaceDao.GetPanmentType(request),

                    WithdrawalOrderNo = $"ts_{request.WithdrawalOrderNo}",
                    WithdrawalAmount = request.WithdrawalAmount,
                    WithdrawalBankName = request.WithdrawalBankName,
                    WithdrawalBankAddress = request.WithdrawalBankAddress,
                    WithdrawalAccountName = request.WithdrawalAccountName,
                    WithdrawalCardNumber = request.WithdrawalCardNumber,
                    //客户银行代码
                    WithdrawalCardBankFlag = request.WithdrawalCardBankFlag,
                    DepositType = request.DepositType
                };
                var paymentRecordId = _paymentRecordDao.Add(paymentRecord);
                if (paymentRecordId > 0)
                {
                    result.Success = true;
                    result.SuccessMessage = "新增付款记录成功!";
                }
                else
                {
                    result.SuccessMessage = "新增付款记录失败!";
                }
            }
            catch (Exception ex) {
                try
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.PaymentRecord_Add.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"新增付款记录失败{ex.Message}";
                    _logRecord.RequestData = JsonConvert.SerializeObject(request);
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 获取付款卡信息
        /// </summary>
        /// <returns></returns>
        public PaymentCardResponse GetPaymentCard(PaymentCardRequest request) {

            var paymentCardResponse = new PaymentCardResponse();

            var companyList = GetCompany(request.CompanyId, 2);

            if (companyList != null && companyList.Any()) {
                paymentCardResponse.CompanyResponse = companyList;
            }


            var bankInfoList = _bankInfoDao.GetBankInfoList();

            if (bankInfoList != null && bankInfoList.Any()) {

                var bankInfoResponse = new List<BankInfoResponse>();

                bankInfoList.ForEach(item => {
                    bankInfoResponse.Add(new BankInfoResponse() {
                        BankCode = item.BankCode,
                        BankName = item.BankName
                    });
                });

                paymentCardResponse.BankInfoResponse = bankInfoResponse;
            }
            return paymentCardResponse;
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        private List<CompanyResponse> GetCompany(int companyId, int level)
        {
            var companyRequest = new EF.Models.Company()
            {
                CompanyId = companyId,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyList = new BaseModel<List<EF.Models.Company>>();

            _companyDao.Get(companyList, companyRequest, level);
            var companyResponse = new List<CompanyResponse>();
            if (companyList.Success)
            {
                foreach (var item in companyList.Result)
                {
                    companyResponse.Add(new CompanyResponse()
                    {
                        CompanyID = item.CompanyId,
                        CompanyName = item.CompanyName,
                        CompanyStatus = item.CompanyStatus
                    });
                }
            }
            return companyResponse;
        }

        /// <summary>
        /// 付款卡查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<PaymentCardResponse> GetPaymentCardPager(PaymentCardQuery query)
        {
            //query.CompanyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            var companyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            if (query.SearchCompanyIds != null && query.SearchCompanyIds.Any()){
                //var bankCardIds = bankCards.Where(p => p.BankName.Contains(query.BankName)).Select(p => p.Bcid).ToList();
                query.CompanyIds = query.SearchCompanyIds.Where(c => companyIds.Contains(c)).ToList();
            }
            else {
                query.CompanyIds = companyIds;
            }
            query.CompanyId = null;
            return _paymentRecordDao.GetPaymentCardPager(query);
        }

        /// <summary>
        /// 付款卡查询
        /// </summary>
        /// <param name="query">查询参数</param>
        public PagedList<PaymentCardResponse> GetRenewMatchCardPager(RenewMatchCardQuery query)
        {
            query.CompanyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            query.CompanyId = null;
            return _paymentRecordDao.GetRenewMatchCardPager(query);
        }

        /// <summary>
        /// 付款记录查询
        /// </summary>
        /// <param name="query"></param>
        public DataGrid<PaymentRecordResponse> GetPaymentRecordPager(PaymentRecordQuery query)
        {
            query.CompanyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);

            var companyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            if (query.SearchCompanyIds != null && query.SearchCompanyIds.Any())
            {
                //var bankCardIds = bankCards.Where(p => p.BankName.Contains(query.BankName)).Select(p => p.Bcid).ToList();
                query.CompanyIds = query.SearchCompanyIds.Where(c => companyIds.Contains(c)).ToList();
            }
            else
            {
                query.CompanyIds = companyIds;
            }
            query.CompanyId = null;

            var pager = new DataGrid<PaymentRecordResponse>();

            try
            {
                pager = _paymentRecordDao.GetPaymentRecordPager(query);
            }
            catch (Exception ex) {

                pager.ErrorMessage = ex.Message;

                //日志
                _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                _logRecord.LogType = LogRecordLogType.Role_Add.GetHashCode();
                _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                _logRecord.CreateDate = DateTime.Now;
                _logRecord.LogRemark = $"付款记录查询失败：{ex.Message}";
                _logRecord.RequestData = ex.StackTrace;
                _logDao.Insert(_logRecord);
            }

            return pager;
        }

        /// <summary>
        /// 收付款记录查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<PaymentRecordResponse> GetPaymentRecordExport(PaymentRecordQuery query)
        {
            var companyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            if (query.SearchCompanyIds != null && query.SearchCompanyIds.Any())
            {
                query.CompanyIds = query.SearchCompanyIds.Where(c => companyIds.Contains(c)).ToList();
            }
            else
            {
                query.CompanyIds = companyIds;
            }
            query.CompanyId = null;

            var pager = new DataGrid<PaymentRecordResponse>();

            try
            {
                pager = _paymentRecordDao.GetPaymentRecordExport(query);
            }
            catch (Exception ex) {

                pager.ErrorMessage = ex.Message;

                //日志
                _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                _logRecord.LogType = LogRecordLogType.Role_Add.GetHashCode();
                _logRecord.LogLevel = (sbyte) LogLevel.Failure.GetHashCode();
                _logRecord.CreateDate = DateTime.Now;
                _logRecord.LogRemark = $"付款记录查询失败：{ex.Message}";
                _logRecord.RequestData = ex.StackTrace;
                _logDao.Insert(_logRecord);
            }

            return pager;
        }

        /// <summary>
        /// 补单
        /// </summary>
        /// <param name="request"></param>
        public JResult ReceiptMakeUp(ReceiptMakeUpRequest request)
        {
            return _paymentRecordDao.ReceiptMakeUp(request);
        }

        /// <summary>
        /// 重新配卡
        /// </summary>
        /// <returns></returns>
        public JResult RenewMatchCard(RenewMatchCardReqeust reqeust)
        {
            var result = _paymentRecordDao.RenewMatchCard(reqeust);
            return result;
        }

        /// <summary>
        /// 验证订单号是否属于当前用户公司
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="orderNo"></param>
        public bool CheckOrder(int companyId,long orderNo) {

            var companyIds = _bankDao.GetCompanyIDList(companyId);

            var paymentRecord = _paymentRecordDao.Get(orderNo);

            if (paymentRecord != null && companyIds.Contains(paymentRecord.CompanyId))
            {
                return true;
            }
            else {
                return false;
            }
        }

        /// <summary>
        /// 银行卡余额异常查询
        /// </summary>
        /// <param name="request"></param>
        public JResult<AdjustBalanceResponse> GetPaymentcardException(PaymentcardExceptionRequest request)
        {
            var result = new JResult<AdjustBalanceResponse>()
            {
                Success = false
            };

            try {
                if (!request.AdjustBalanceRid.HasValue) {
                    throw new Exception("参数错误，请联系管理员！");
                }

                var bankCard = _bankDao.GetById(request.BackCardId);
                if (bankCard.AdjustBalanceRid != request.AdjustBalanceRid) {
                    throw new Exception("参数错误，请联系管理员！");
                }

                var adjustBalance = _adjustBalanceDao.Get(bankCard.AdjustBalanceRid.Value);
                if (adjustBalance != null) {
                    var adjustBalanceResponse = new AdjustBalanceResponse()
                    {
                        Rid = adjustBalance.Rid.ToString(),
                        Amount = adjustBalance.Amount,
                        BeforeBalance = adjustBalance.BeforeBalance,
                        AfterBalance = adjustBalance.AfterBalance,
                        CardBcid = adjustBalance.CardBcid,
                        CardNumber = adjustBalance.CardNumber,
                        CreateName = adjustBalance.CreateName,
                        CreateDbdate = adjustBalance.CreateDbdate,
                        CreateDate = adjustBalance.CreateDate,
                        CreateRemark = adjustBalance.CreateRemark,
                        AdjustStatus = adjustBalance.AdjustStatus,
                        CompanyId = adjustBalance.CompanyId,
                    };
                    if (adjustBalance.CardBcid.HasValue) {
                        var model = _bankDao.GetById(adjustBalance.CardBcid.Value);
                        if (model != null) {
                            adjustBalanceResponse.BankName = model.BankName;
                            adjustBalanceResponse.CardName = model.CardName;
                        }
                    }

                    var company = _companyDao.GetById(adjustBalance.CompanyId);
                    if (company != null) {
                        adjustBalanceResponse.CompanyName = company.CompanyName;
                    }
                    result.Data = adjustBalanceResponse;

                    result.Success = true;
                }
            }
            catch (Exception ex) {
                result.ErrorMessage = ex.Message;
            }


            return result;
        }

        /// <summary>
        /// 改变渠道
        /// </summary>
        /// <param name="request"></param>
        public JResult ChangeChannels(ChangeChannelsRequest request)
        {
            return _paymentRecordDao.ChangeChannels(request);
        }

        /// <summary>
        /// 改变公司
        /// </summary>
        /// <param name="request"></param>
        public JResult ChangeCompany(ChangeCompanyRequest request)
        {
            var companyIds = _bankDao.GetCompanyIDList(request.LoginCompanyId);

            if (!companyIds.Contains(request.CompanyId)) {
                return new JResult() {
                    Success = false,
                    ErrorMessage = "无效公司编号"
                };
            }
            return _paymentRecordDao.ChangeCompany(request);
        }
    }
}
